<template>
  <div class="dashboard-container">
    <div class="coffee-bg"></div>
    <el-row :gutter="24">
      <el-col :span="6">
        <el-card class="dashboard-card">
          <div class="stat-title">今日销售额</div>
          <div class="stat-value">¥{{ salesToday }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="dashboard-card">
          <div class="stat-title">今日订单数</div>
          <div class="stat-value">{{ ordersToday }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="dashboard-card">
          <div class="stat-title">库存预警</div>
          <div class="stat-value warning">{{ lowStockCount }} 项</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="dashboard-card">
          <div class="stat-title">营业时间</div>
          <div class="stat-value">{{ businessHours }}</div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="24" style="margin-top:32px">
      <el-col :span="12">
        <el-card class="dashboard-card">
          <div class="chart-title">近7天销售趋势</div>
          <div ref="salesChart" style="height:300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="dashboard-card">
          <div class="chart-title">热销商品TOP5</div>
          <div ref="hotChart" style="height:300px"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  data() {
    return {
      salesToday: 0,
      ordersToday: 0,
      lowStockCount: 0,
      businessHours: '',
      sales7: [],
      hotProducts: []
    }
  },
  mounted() {
    this.loadStats()
    this.initCharts()
  },
  watch: {
    '$route'() {
      this.loadStats()
      this.initCharts()
    }
  },
  methods: {
    getOrderDate(order) {
      if (!order.createTime) return '';
      // ISO 格式
      if (/^\d{4}-\d{2}-\d{2}/.test(order.createTime)) {
        return order.createTime.slice(0, 10);
      }
      // 本地格式
      const d = new Date(order.createTime);
      if (!isNaN(d)) {
        const y = d.getFullYear();
        const m = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${y}-${m}-${day}`;
      }
      return '';
    },
    loadStats() {
      // 模拟数据，实际可从localStorage或后端获取
      const orders = JSON.parse(localStorage.getItem('orders') || '[]')
      const today = new Date().toISOString().slice(0, 10)
      this.salesToday = orders.filter(o => this.getOrderDate(o) === today).reduce((sum, o) => sum + (o.totalAmount || 0), 0)
      this.ordersToday = orders.filter(o => this.getOrderDate(o) === today).length
      // 近7天销售
      const sales7 = []
      for (let i = 6; i >= 0; i--) {
        const d = new Date(Date.now() - i * 24 * 3600 * 1000)
        const ds = d.toISOString().slice(0, 10)
        const daySales = orders.filter(o => this.getOrderDate(o) === ds).reduce((sum, o) => sum + (o.totalAmount || 0), 0)
        sales7.push({ date: ds, value: daySales })
      }
      this.sales7 = sales7
      // 热销商品
      const productMap = {}
      orders.forEach(o => {
        (o.items || []).forEach(item => {
          if (!productMap[item.name]) productMap[item.name] = 0
          productMap[item.name] += item.quantity || 0
        })
      })
      this.hotProducts = Object.entries(productMap).sort((a, b) => b[1] - a[1]).slice(0, 5)
      // 库存预警
      const inventory = JSON.parse(localStorage.getItem('inventory') || '[]')
      this.lowStockCount = inventory.filter(i => i.currentStock <= i.minStock).length
      // 营业时间
      const settings = JSON.parse(localStorage.getItem('systemSettings') || 'null')
      if (settings && settings.businessHours) {
        this.businessHours = settings.businessHours
          .map(t => {
            const d = typeof t === 'string' ? new Date(t) : t
            return d instanceof Date && !isNaN(d) ? d.toTimeString().slice(0,5) : t
          })
          .join(' - ')
      } else {
        this.businessHours = '08:00 - 22:00'
      }
    },
    initCharts() {
      this.$nextTick(() => {
        // 销售趋势
        const salesChart = echarts.init(this.$refs.salesChart)
        salesChart.setOption({
          xAxis: { type: 'category', data: this.sales7.map(i => i.date) },
          yAxis: { type: 'value' },
          series: [{ data: this.sales7.map(i => i.value), type: 'line', smooth: true, areaStyle: {} }],
          tooltip: { trigger: 'axis' },
          color: [this.getThemeColor()]
        })
        // 热销商品
        const hotChart = echarts.init(this.$refs.hotChart)
        hotChart.setOption({
          xAxis: { type: 'category', data: this.hotProducts.map(i => i[0]) },
          yAxis: { type: 'value' },
          series: [{ data: this.hotProducts.map(i => i[1]), type: 'bar', barWidth: 30 }],
          tooltip: { trigger: 'axis' },
          color: [this.getThemeColor()]
        })
      })
    },
    getThemeColor() {
      const settings = JSON.parse(localStorage.getItem('systemSettings') || 'null')
      return (settings && settings.themeColor) || '#409EFF'
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 40px;
  min-height: 100vh;
  background: linear-gradient(135deg, #e7d2ba 0%, #b08968 100%);
  position: relative;
  overflow: hidden;
}
.coffee-bg {
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 0;
  pointer-events: none;
  background: url('https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/72x72/2615.png') repeat 0 0/120px auto;
  opacity: 0.06;
}
.dashboard-card {
  border-radius: 16px;
  box-shadow: 0 4px 18px 0 rgba(124, 79, 34, 0.10);
  border: 1px solid #e0c3a0;
  background: rgba(255, 255, 255, 0.96);
  min-height: 120px;
}
.stat-title {
  color: #a47149;
  font-size: 15px;
  font-weight: 500;
  letter-spacing: 1px;
}
.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-top: 10px;
  color: #7c4f22;
  font-family: 'Segoe Script', 'Comic Sans MS', cursive, sans-serif;
}
.stat-value.warning {
  color: #e6a23c;
}
.chart-title {
  font-size: 17px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #7c4f22;
  letter-spacing: 1px;
  font-family: 'Segoe Script', 'Comic Sans MS', cursive, sans-serif;
}
</style> 